<template>
  <div v-if="showInstaller" class="installer">
    <!-- 瀏覽器支援加入主畫面 -->
    <div
      v-if="installType === INSTALL_TIP_TYPE.ADD_TO_HOMESCREEN"
      class="panel bg-surface d-flex flex-column gap-col-8"
      :class="{ close }"
      @transitionend="onTransitionEnd"
    >
      <div class="head d-flex">
        <div class="left"></div>
        <div class="center flex-grow-1 font-weight-500 line-height-140">{{ $t('info.installOnIOS') }}</div>
        <div class="right pointer" @click="closePanel">
          <Icon name="close" size="20"></Icon>
        </div>
      </div>
      <div class="flow d-flex justify-center align-center gap-row-16">
        <div class="step d-flex flex-column align-center align-self-start gap-col-8">
          <div class="dir bg-gray-x d-flex justify-center align-center">
            <Icon name="sharing" size="20"></Icon>
          </div>
          <div class="desc text-center font-size-14 font-weight-500 line-height-140">{{ $t('info.tapShare') }}</div>
        </div>
        <Icon name="arrowRight" size="20"></Icon>
        <div class="step d-flex flex-column align-center align-self-start gap-col-8">
          <div class="dir bg-gray-x d-flex justify-center align-center">
            <Icon name="install" size="20"></Icon>
          </div>
          <div class="desc text-center font-size-14 font-weight-500 line-height-140">
            {{ $t('info.addToHomescreen') }}
          </div>
        </div>
        <Icon name="arrowRight" size="20"></Icon>
        <div class="step d-flex flex-column align-center align-self-start gap-col-8">
          <img class="dir" src="@/assets/images/app-icon.png" alt="app icon" />
          <div class="desc text-center font-size-14 font-weight-500 line-height-140">{{ $t('info.addFantasi') }}</div>
        </div>
      </div>
    </div>

    <!-- iOS 16.4 以下(不包含16.4) Chrome 瀏覽器沒有加入主畫面，請他回 Safari 安裝 -->
    <div
      v-else-if="installType === INSTALL_TIP_TYPE.TO_SAFARI"
      class="panel bg-surface d-flex flex-column gap-col-8"
      :class="{ close }"
      @transitionend="onTransitionEnd"
    >
      <div class="head d-flex">
        <div class="left"></div>
        <div class="center flex-grow-1">{{ $t('info.goToSafariInstall') }}</div>
        <div class="right pointer" @click="closePanel">
          <Icon name="close" size="20"></Icon>
        </div>
      </div>
      <div class="flow d-flex flex-column align-center gap-col-8">
        <img src="@/assets/images/safari-logo.png" alt="safari logo" />
        <div class="font-size-16 font-weight-500 line-height-140">{{ $t('info.openLinkOnSafari') }}</div>
        <button
          class="primary-btn primary-gradient font-size-14 font-weight-500 line-height-140 pointer"
          @click="copyInstallLink"
        >
          <span class="desc font-size-14 font-weight-500 line-height-140">{{ $t('info.copyLink') }}</span>
          <Icon name="copy" size="12"></Icon>
        </button>
      </div>
    </div>

    <!-- 支援 beforeinstallprompt 的安裝方式 -->
    <div
      v-else-if="installType === INSTALL_TIP_TYPE.INSTALL_PROMPT"
      class="panel bg-surface d-flex flex-column gap-col-8"
      :class="{ close }"
      @transitionend="onTransitionEnd"
    >
      <div class="head d-flex">
        <div class="left"></div>
        <div class="center flex-grow-1">{{ $t('info.installAsApp') }}</div>
        <div class="right pointer" @click="closePanel">
          <Icon name="close" size="20"></Icon>
        </div>
      </div>
      <div class="flow d-flex justify-center align-center gap-row-24">
        <div class="step d-flex flex-column align-center gap-col-8">
          <img class="dir" src="@/assets/images/app-icon.png" alt="app icon" />
          <div class="desc text-center font-size-14 font-weight-500 line-height-140">{{ $t('info.addFantasi') }}</div>
        </div>
        <button
          class="primary-btn primary-gradient font-size-14 font-weight-500 line-height-140 pointer"
          @click="onInstallClick"
        >
          <Icon name="download" size="12"></Icon>
          <span class="desc font-size-14 font-weight-500 line-height-140">{{ $t('info.installNow') }}</span>
        </button>
      </div>
      <div
        class="text-primary text-center font-size-14 font-weight-500 line-height-140 pointer"
        @click="openInstallerTutorial"
      >
        {{ $t('info.cannotInstall') }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useAppStore } from '@/store/app'
import { useInstallTutorStore } from '@/store/install-tutor'
import { getInstaller } from '@/utils/installer'
import { useCopyToClipboard } from '@/compositions/utils/copyToClipboard'
import { trackEvent } from '@/gtm'

const INSTALL_TIP_TYPE = {
  NONE: 0,
  ADD_TO_HOMESCREEN: 1, // 瀏覽器支援加入主畫面
  TO_SAFARI: 2, // iOS 16.4 以下(不包含16.4) Chrome 瀏覽器沒有加入主畫面，請他回 Safari 安裝
  INSTALL_PROMPT: 3, // 支援 beforeinstallprompt 的安裝方式
}

const appStore = useAppStore()
const { showInstaller } = storeToRefs(appStore)
const { closeInstaller } = appStore

const { open, STATE } = useInstallTutorStore()

function openInstallerTutorial() {
  closeInstaller()
  open(STATE.ANDROID_CHROME)
}

const close = ref(true)
let closeTimerId
watch(
  showInstaller,
  (v) => {
    if (v) {
      closeTimerId = setTimeout(() => (close.value = false), 50)
    }
  },
  { immediate: true },
)

const installType = computed(() => {
  if (showInstaller.value) {
    if (isIOS()) {
      if (isSafari()) {
        return INSTALL_TIP_TYPE.ADD_TO_HOMESCREEN
      } else {
        if (isIOSge16_4()) {
          return INSTALL_TIP_TYPE.ADD_TO_HOMESCREEN
        } else {
          return INSTALL_TIP_TYPE.TO_SAFARI
        }
      }
    } else {
      if (import.meta.env.DEV) {
        return INSTALL_TIP_TYPE.INSTALL_PROMPT
      }
      if (getInstaller()) {
        return INSTALL_TIP_TYPE.INSTALL_PROMPT
      } else {
        clearTimeout(closeTimerId)
        closeInstaller()
        return INSTALL_TIP_TYPE.NONE
      }
    }
  }
  return INSTALL_TIP_TYPE.NONE
})

watch(installType, (v) => {
  switch (v) {
    case INSTALL_TIP_TYPE.ADD_TO_HOMESCREEN:
      trackEvent({ key: 52 })
      break
    case INSTALL_TIP_TYPE.TO_SAFARI:
      trackEvent({ key: 53 })
      break
    case INSTALL_TIP_TYPE.INSTALL_PROMPT:
      trackEvent({ key: 54 })
      break
  }
})

function closePanel() {
  close.value = true
}

function onTransitionEnd() {
  if (close.value) {
    closeInstaller()
  }
}

async function onInstallClick() {
  const installer = getInstaller()
  if (installer) {
    trackEvent({ key: 55 })
    await installer.prompt()
    closeInstaller()
  }
}

function isIOS() {
  return (
    ['iPad Simulator', 'iPhone Simulator', 'iPod Simulator', 'iPad', 'iPhone', 'iPod'].includes(navigator.platform) ||
    // iPad on iOS 13 detection
    (navigator.userAgent.includes('Mac') && 'ontouchend' in document)
  )
}

function isSafari() {
  return /Version\/[\d\\.]+.*Safari/.test(navigator.userAgent)
}

function isIOSge16_4() {
  const iOSVersionMatch = navigator.userAgent.match(/(iPhone|iPad|iPod).*?OS (\d+)_(\d+)/) || []
  const [, , major, minor] = iOSVersionMatch
  if (+major > 16) {
    return true
  } else if (+major === 16) {
    return +minor >= 4
  } else {
    return false
  }
}

const { copy } = useCopyToClipboard()
function copyInstallLink() {
  const url = window.location.origin + '?install-tutor=1'
  copy(url)
  trackEvent({ key: 57 })
}
</script>

<style lang="scss" scoped>
.installer {
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.6);
  position: absolute;
  top: 0;
  z-index: 1; // MediaWall.vue 當中的 tab sticky 時需要設定 z-index，會跟這邊衝突所以這邊也得設定至少同層級

  .panel {
    width: 100%;
    padding: 0.25rem 0 1rem;
    border-radius: 0.625rem 0.625rem 0 0;
    position: absolute;
    bottom: 0;
    transition: transform 0.3s;

    &.close {
      transform: translateY(100%);
    }

    .head {
      padding: 0.5rem;
      .center {
        text-align: center;
      }

      .left {
        width: 1.25rem;
        height: 1.25rem;
      }
    }

    .flow {
      padding: 0 1rem;

      .step {
        .dir {
          width: 3.125rem;
          height: 3.125rem;
          border-radius: 3.125rem;
        }
        img.dir {
          box-shadow: 0rem 0rem 0.4375rem 0rem rgba(255, 15, 0, 0.68);
        }
      }
      button {
        .desc {
          padding: 0 0.5rem;
        }
      }
    }
  }
}
</style>
